package com.go.running.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.go.core.bean.RunningScore;
import com.go.dto.EventDto;
import com.go.dto.JsonDtoWrapper;
import com.go.enums.ApiCode;
import com.go.running.service.RunningService;
import com.go.timer.MyTimerTask;
import com.go.timer.TimerThread;
import com.go.util.TimeUtil;
import com.go.websocket.MessageService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

@Slf4j
@RestController
@RequestMapping("running")
public class RunningController {

    @Value("${small.timeout}")
    private Integer timeout;

    @Autowired
    MessageService messageService;
    @Autowired
    RunningService runningService;

    @GetMapping("start")
    public JsonDtoWrapper PbS(@RequestParam("uuid") String uuid, @RequestParam("name") String name){
        TimeUtil.UUID = uuid; // 记录玩家的uuid
        RunningScore sb = new RunningScore();
        sb.setName(name);
        sb.setUuid(uuid);
        RunningScore save = runningService.save(sb);
        if (null != save){
            EventDto eventDto = new EventDto();
            Map<String, String> map = new HashMap<>();
            map.put("uuid",uuid);
            map.put("name",name);
            map.put("avator",uuid);
            eventDto.build(ApiCode.GAME_START);
            eventDto.setData(map);
            eventDto.setTimeout(timeout);
            TimeUtil.starttime = System.currentTimeMillis();
            TimeUtil.success=true; // 防止第一次 finnish 被置为 false 之后，没改回来
            // 启动timer
//            new Thread(new TimerThread()).start();
            new Timer().schedule(new MyTimerTask("run"), timeout*1000);
            return messageService.sendSingnalToPC(1,new Gson().toJson(eventDto));
        }
        return null;
    }

    // 汇报成绩，并向websocket发送排行榜
    @PostMapping("finnish")
    public JsonDtoWrapper Finnish(@RequestBody String scoreMap){
        // 判断时间是否超出
        if(System.currentTimeMillis() < (TimeUtil.starttime + timeout*1000)) TimeUtil.success = false;
        JsonDtoWrapper jo = new JsonDtoWrapper();
        if (null == scoreMap) return jo;
        String uuid = "";
        try{
            JSONObject jsonObject = JSON.parseObject(scoreMap);
            uuid = jsonObject.getString("uuid");
            int score = Integer.valueOf(jsonObject.getString("score"));
            runningService.updateScoreByUUID(uuid, score); // 更新成绩
        }catch(Exception e){
            e.printStackTrace();
        }
        // 向大屏发送排行榜
        Map<String, Object> dataMap = new HashMap<>();
        RunningScore playerByUUID = runningService.findPlayerByUUID(uuid);
        List<RunningScore> scoreBorad = runningService.getScoreBorad();
        dataMap.put("scoreboard",scoreBorad);
        dataMap.put("current",playerByUUID);

        // 发送给大屏
        EventDto eventDto = new EventDto();
        eventDto.setData(dataMap);
        eventDto.build(ApiCode.GAME_STOP);
        return messageService.sendSingnalToPC(1,new Gson().toJson(eventDto));
    }

}
